package com.graduate.controller;


import com.db.pojo.Associator;
import com.graduate.exception.BizException;
import com.graduate.utils.BaseServiceUtils;
import com.graduate.service.AssociatorService;
import com.graduate.utils.RespBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 会员Controller
 *
 * @Createtime : 2020-04-01
 * @Creator : jingchu
 */
@RestController
//@Controller(配合ResponseBody使用)
@EnableAutoConfiguration
@RequestMapping("/associator")
public class AssociatorController extends BaseServiceUtils {
    @Autowired
    private AssociatorService associatorService;

    //value触发的什么情况时进行重试,maxAttempts最大重试次数,delay延迟时间,multiplier上次延迟时间是这次的倍数
    @Retryable(value = BizException.class, maxAttempts = 3, backoff = @Backoff(delay = 2000, multiplier = 1.5))
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @Transactional
    public RespBody login(@RequestBody Map<String, Object> requesetMap) {
        /**
         * 服务流程
         * 1.根据openid查询是否注册过
         * 2.没注册过注册
         * 3.注册完毕后返回个人信息
         */
        String openid = (String) requesetMap.get("openid");
        String table = "associator";
        Map<String, Object> map = new HashMap<>();
        map.put("openid", openid);
        map.put("table", table);
        String id="";
        Associator associator = associatorService.getAssociatorByOpenid(openid);
        if (associator == null) {
            associator = new Associator();
            id = insert(map);
            if(!StringUtils.isEmpty(id)){
                map.put("op_type", "A01");
                map.put("op_desc", "会员注册");
                insertRecords(map);
            }
        }
        return RespBody.success(associator);
    }


}
